package com.wst.system.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class RandomStringGenerator {

    // 定义所有可能的字符（大小写字母）
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    // 生成随机字符串的方法
    public static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            // 从 CHARACTERS 中随机选择一个字符
            int randomIndex = random.nextInt(CHARACTERS.length());
            char randomChar = CHARACTERS.charAt(randomIndex);
            sb.append(randomChar);
        }

        return sb.toString();
    }

    // 将字符串转换为字符数组
    public static char[] convertStringToCharArray(String str) {
        return str.toCharArray();
    }

    // 随机且不重复地插入字符串到字符数组中，并记录插入的下标
    public static char[] insertStringRandomly(char[] originalArray, String insertStr, List<Integer> insertedIndices) {
        Random random = new Random();
        char[] insertArray = insertStr.toCharArray();
        char[] newArray = new char[originalArray.length ];

        // 复制原始数组到新数组
        System.arraycopy(originalArray, 0, newArray, 0, originalArray.length);

        // 生成随机且不重复的下标
        List<Integer> availableIndices = new ArrayList<>();
        for (int i = 0; i < newArray.length; i++) {
            availableIndices.add(i);
        }
        Collections.shuffle(availableIndices, random);

        // 插入字符并记录下标
        for (int i = 0; i < insertArray.length; i++) {
            int insertIndex = availableIndices.get(i);
            newArray[insertIndex] = insertArray[i];
            insertedIndices.add(insertIndex); // 记录插入的下标
        }

        return newArray;
    }

    public static void main(String[] args) {
        // 生成随机英文字符串
        String randomString = generateRandomString(200); // 生成长度为 20 的随机字符串
        System.out.println("随机生成的字符串: " + randomString);

        // 将字符串转换为字符数组
        char[] charArray = convertStringToCharArray(randomString);
        System.out.println("字符数组: " + new String(charArray));

        // 要插入的字符串
        String insertStr = "NTg3ODU3NjcwOTQzNzA4Mg==";

        // 记录插入的下标
        List<Integer> insertedIndices = new ArrayList<>();

        // 随机且不重复地插入字符串
        char[] newArray = insertStringRandomly(charArray, insertStr, insertedIndices);
        System.out.println("插入后的字符数组: " + new String(newArray));
        System.out.println("插入的下标: " + insertedIndices);
        StringBuilder stringBuilder=new StringBuilder();
        insertedIndices.forEach((e)->{
            stringBuilder.append(newArray[e]);
        });
        System.out.println(stringBuilder.toString());
    }
}
